<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="文件名称" prop="fileName">
          <el-input
            v-model="queryParams.fileName"
            placeholder="请输入文件名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="queryParams.fileType" placeholder="文件类型" clearable style="width: 200px">
            <el-option label="图片" value="IMAGE" />
            <el-option label="文档" value="DOCUMENT" />
            <el-option label="视频" value="VIDEO" />
            <el-option label="音频" value="AUDIO" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>
        <el-form-item label="上传者" prop="uploader">
          <el-input
            v-model="queryParams.uploader"
            placeholder="请输入上传者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 文件表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="fileList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="文件名称" align="center" prop="fileName" :show-overflow-tooltip="true" />
        <el-table-column label="文件类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getFileTypeTag(scope.row.fileType)">
              {{ getFileTypeText(scope.row.fileType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文件大小" align="center" prop="fileSize" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.fileSize) }}
          </template>
        </el-table-column>
        <el-table-column label="上传者" align="center" prop="uploaderName" width="120" />
        <el-table-column label="下载次数" align="center" prop="downloadCount" width="100" />
        <el-table-column label="是否分享" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.isShared ? 'success' : 'info'">
              {{ scope.row.isShared ? '已分享' : '私有' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="上传时间" align="center" prop="uploadTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.uploadTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="Download"
                @click="handleDownload(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >下载</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handlePreview" icon="View">预览</el-dropdown-item>
                    <el-dropdown-item command="handleShare" icon="Share">分享管理</el-dropdown-item>
                    <el-dropdown-item command="handleVersions" icon="Clock">版本历史</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getFilePage, deleteFile, downloadFile } from '@/api/disk'
import { useRouter } from 'vue-router'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const total = ref(0)
const fileList = ref([])
const queryFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  fileName: undefined,
  fileType: undefined,
  uploader: undefined
})

// 获取文件列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getFilePage(queryParams)
    if (response.code === 200) {
      fileList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取文件列表失败')
    }
  } catch (error) {
    console.error('获取文件列表失败:', error)
    ElMessage.error('获取文件列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
}

// 下载文件
const handleDownload = async (row) => {
  try {
    const response = await downloadFile(row.id)
    const url = window.URL.createObjectURL(new Blob([response]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', row.fileName)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败')
  }
}

// 删除按钮操作
const handleDelete = (row) => {
  const fileIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除文件编号为"' + fileIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteFile(fileIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除文件失败:', error)
      ElMessage.error('删除文件失败')
    }
  }).catch(() => {})
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handlePreview':
      handlePreview(row)
      break
    case 'handleShare':
      handleShare(row)
      break
    case 'handleVersions':
      handleVersions(row)
      break
    default:
      break
  }
}

// 预览文件
const handlePreview = (row) => {
  router.push(`/disk/file/${row.id}/preview`)
}

// 分享管理
const handleShare = (row) => {
  router.push(`/disk/file/${row.id}/share`)
}

// 版本历史
const handleVersions = (row) => {
  router.push(`/disk/file/${row.id}/versions`)
}

// 工具函数
const getFileTypeTag = (fileType) => {
  const typeMap = {
    'IMAGE': 'success',
    'DOCUMENT': 'primary',
    'VIDEO': 'warning',
    'AUDIO': 'info',
    'OTHER': 'default'
  }
  return typeMap[fileType] || 'default'
}

const getFileTypeText = (fileType) => {
  const textMap = {
    'IMAGE': '图片',
    'DOCUMENT': '文档',
    'VIDEO': '视频',
    'AUDIO': '音频',
    'OTHER': '其他'
  }
  return textMap[fileType] || fileType
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}
</style>
